package online.dgyj.tp_link;

import android.annotation.SuppressLint;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tplink.sdk.tpopensdk.TPOpenSDK;
import com.tplink.sdk.tpopensdk.TPPlayer;
import com.tplink.sdk.tpopensdk.TPSDKContext;
import com.tplink.sdk.tpopensdk.common.TPSDKCommon;
import com.tplink.sdk.tpopensdk.openctx.IPCDevice;
import com.tplink.sdk.tpopensdk.openctx.IPCDeviceContext;
import com.tplink.sdk.tpopensdk.openctx.IPCReqListener;
import com.tplink.sdk.tpopensdk.openctx.IPCReqResponse;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button recordBtn;
    private ImageButton imageBtn;
    private FrameLayout playFrameLayout;
    private static final String IPC_IP = "172.18.6.13";     // IPC设备的IP地址
    private static final int IPC_PORT = 80;     // IPC设备的端口，默认为80
    private IPCDeviceContext ipcDeviceContext;      // IPC设备上下文
    private IPCDevice ipcDevice;       // IPC设备
    private TPPlayer tpPlayer;  // 播放器
    private SimpleDateFormat simpleDateFormat;
    private int x = 0, y = 0;   // 摄像机坐标
    private boolean recordStatus = false, sysStatus = false;    // 标志
    private final String filePath = "/storage/emulated/0/DCIM/TPLINK/";     // 文件的保存路径

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        // 检测路径是否存在，如果路径不存在则自动创建
        File file = new File(filePath);
        if (!file.exists()) {
            Log.i("FilePath", "路径不存在，开始创建");
            if (file.mkdirs())
                Log.i("MkdirFilePath", "OK!");
            else
                Log.e("MkdirFilePath", "Error!");
        }

        // 实例化视图
        Button linkBtn = findViewById(R.id.linkBth);
        Button upBtn = findViewById(R.id.upBth);
        Button downBtn = findViewById(R.id.downBth);
        Button leftBtn = findViewById(R.id.leftBth);
        Button rightBtn = findViewById(R.id.rightBth);
        Button snapshotBtn = findViewById(R.id.snapshotBtn);
        imageBtn = findViewById(R.id.imageBtn);
        recordBtn = findViewById(R.id.recordBtn);
        playFrameLayout = findViewById(R.id.frameLayout);

        // 设置点击监听
        linkBtn.setOnClickListener(this);
        upBtn.setOnClickListener(this);
        downBtn.setOnClickListener(this);
        leftBtn.setOnClickListener(this);
        rightBtn.setOnClickListener(this);
        snapshotBtn.setOnClickListener(this);
        recordBtn.setOnClickListener(this);
        imageBtn.setOnClickListener(this);

        initIPCLink();  // 初始化IPC连接
        setImage(); // 设置图像
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.upBth) {
            y += 15;
            ctrlIPC(); // 控制IPC
        }
        if (view.getId() == R.id.downBth) {
            y -= 15;
            ctrlIPC(); // 控制IPC
        }
        if (view.getId() == R.id.leftBth) {
            x -= 15;
            ctrlIPC(); // 控制IPC
        }
        if (view.getId() == R.id.rightBth) {
            x += 15;
            ctrlIPC(); // 控制IPC
        }
        if (view.getId() == R.id.linkBth) {
            if (!sysStatus) {
                if (tpPlayer == null) {
                    // 获取TPPlayer播放器并设置播放句柄
                    tpPlayer = TPOpenSDK.getInstance().createPlayer(getApplicationContext()).setViewHolder(playFrameLayout);
                }
                sysStatus = true;
                // 开启预览画面
                tpPlayer.startRealPlay(ipcDevice, 1);
            } else {
                sysStatus = false;
                tpPlayer.stop();    // 停止播放
                tpPlayer.release(); // 销毁播放器
                playFrameLayout.removeAllViews();   // 清除播放视图
                tpPlayer = null;
            }
        }
        if (view.getId() == R.id.recordBtn) {
            if (sysStatus) {
                if (!recordStatus) {
                    recordStatus = true;
                    Long time = new Date().getTime();
                    String url = filePath + simpleDateFormat.format(time) + ".mp4";
                    tpPlayer.startRecord(url);
                    Log.i("record", "开始录制");
                    Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show();
                    recordBtn.setText("停止录制");
                } else {
                    recordStatus = false;
                    tpPlayer.stopRecord();
                    Log.i("record", "结束录制");
                    Toast.makeText(this, "录制完成，文件保存在" + filePath, Toast.LENGTH_SHORT).show();
                    recordBtn.setText("录制");
                }
            } else {
                Toast.makeText(this, "请先开启监控画面", Toast.LENGTH_SHORT).show();
            }
        }
        if (view.getId() == R.id.snapshotBtn) {
            if (sysStatus) {
                Long time = new Date().getTime();
                String url = filePath + simpleDateFormat.format(time) + ".png";
                System.out.println(url);
                if (tpPlayer.snapshot(url) == TPSDKCommon.ErrorCode.IPC_EC_OK) {
                    Log.i("snapshot", "OK!");
                    Toast.makeText(this, "截图成功，文件保存在" + filePath, Toast.LENGTH_SHORT).show();
                    setImage();
                } else {
                    Log.i("snapshot", "Error!");
                    Toast.makeText(this, "截图失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "请先开启监控画面", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 初始化IPC连接
     */
    public void initIPCLink() {
        TPSDKContext tpsdkContext = TPOpenSDK.getInstance().getSDKContext();    // 获取SDK上下文
        tpsdkContext.appReqStart(true, null);   // 开启APP底层
        ipcDeviceContext = tpsdkContext.getDevCtx();        // 获取IPC设备上下文
        ipcDevice = new IPCDevice(ipcDeviceContext.initDev(IPC_IP, IPC_PORT));  // 获取IPC设备
        ipcDeviceContext.reqLogin(ipcDevice, "123456", new IPCReqListener() {
            /**
             * IPC登录鉴权
             * @
             * @param ipcReqResponse  登录鉴权回调
             * @return Error code
             */
            @Override
            public int callBack(IPCReqResponse ipcReqResponse) {
                ipcDeviceContext.reqConnectDev(ipcDevice, new IPCReqListener() {
                    /**
                     * 获取IPC功能集
                     * @param ipcReqResponse 获取IPC功能集回调
                     * @return Error code
                     */
                    @Override
                    public int callBack(IPCReqResponse ipcReqResponse) {
                        ipcDeviceContext.reqGetVideoPort(ipcDevice, new IPCReqListener() {
                            /**
                             * 获取视频播放端口
                             * @param ipcReqResponse 获取视频播放端口回调
                             * @return Error code
                             */
                            @Override
                            public int callBack(IPCReqResponse ipcReqResponse) {
                                // 获取TPPlayer播放器并设置播放句柄
                                tpPlayer = TPOpenSDK.getInstance().createPlayer(getApplicationContext()).setViewHolder(playFrameLayout);
                                return 0;
                            }
                        });
                        return 0;
                    }
                });
                return 0;
            }
        });
    }

    /**
     * 控制摄像头云台
     */
    public void ctrlIPC() {
        ipcDeviceContext.reqMotorMoveTo(ipcDevice, null, x, y, -1);
    }

    /**
     * 设置图像
     */
    private void setImage() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    File file = new File(filePath);
                    String[] fileList = file.list();
                    if (fileList != null && fileList.length > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                imageBtn.setImageBitmap(BitmapFactory.decodeFile(filePath + fileList[fileList.length - 1]));
                            }
                        });
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
